var notify = require("../lib/notify");
var role = require("../lib/role");
var s_key_cache = {};
module.exports = {
	prefix: "/notify",
	init: function(app) {
		notify.init(app, "/sock_notify");
		notify.on("init", function(conn, data) {
			var s_key = data.s_key;
			if (!s_key) {
				throw "连接参数错误"
			}
			var s_info = s_key_cache[s_key];
			if (!s_info) {
				throw "连接密匙无效"
			} else {
				s_key_cache[s_key] = null; //只有一次有效性，用过后就销毁
			}
			conn.s_key = s_key;
			conn.s_info = s_info;
			var loginer_id = s_info.id;
			(notify.conns[loginer_id] || (notify.conns[loginer_id] = [])).push(conn);
			notify.send(conn, "init-success", conn.id);
		});
		notify.on("close", function(conn) {
			var s_info = s_key_cache[conn.s_key];
			var loginer_id = s_info.id;
			var conSet = notify.conns[loginer_id];
			if (conSet) {
				var index = conSet.indexOf(conn);
				if (index !== -1) {
					conSet.splice(index, 1);
				}
				// if (conSet.length === 0) {
				// 	notify.conns[loginer_id] = null;
				// }
			}
		});
	},
	get: {
		"/test/:eventName": function() {
			var eventName = this.params.eventName || "json";
			var user = role.getUser(this);
			var connSet = role.getUserSockSet(user._id);
			if (!connSet) {
				throw "未建立连接"
			}
			notify.send(connSet, eventName, "testStringehehheeh")
			this.body = ResponObj("json", "已经发送");
		}
	},
	post: {
		//通过已经登录的对象权限获取Sock连接的安全key
		"/ask_con_key": function() {
			var body = this.request.body;
			var type = body.type;
			var s_key = type + "_socket_" + (new Date).format("YYYY-MM-DD[hh:mm:ss]") + "_" + Math.random();
			switch (type) {
				case "user":
					var loginer = role.getUser(this);
					break;
				case "anonymous":
					var loginer = role.getAnonymous(this);
					break;
				case "admin":
					var loginer = role.getAdmin(this);
					break;
			}
			if (loginer) {
				//首先要有登录的信息，如果登录了，就可以将sock连接进行缓存，连接者将得到连接密钥s_key
				s_key_cache[s_key] = {
					type: type,
					id: loginer._id
				};
				this.body = ResponObj("json", {
					s_key: s_key
				});
			} else {
				throw "权限不足"
			}
		}
	}
}